<template>
  <div>
    <searchCard @onSearch="searchFn" @onReset="resetFn">
      <el-form :inline="true" @keyup.enter="searchFn">
        <el-form-item label="导入日期：">
          <pb-date-picker v-model="planDateRang" placeholder="请输入" @change="dateChange"></pb-date-picker>
        </el-form-item>
      </el-form>
    </searchCard>
    <div class="divide-css"></div>
    <!-- 表格区 -->
    <div class="flex-1">
      <pb-card padding="0" height="100%">
        <div class="main-box">
          <pb-table :column="tableColumn" :tableData="tableData" :bottomElement="['pb-page']">
            <template #operate="{ row }">
              <pb-button size="small" text @click="downHistryFn(row)"
                v-hasPerm="'center:Analysis:ls-down'">下载</pb-button>
            </template>
          </pb-table>
          <pb-pagination v-model:currentPage="pages.currentPage" v-model:pageSize="pages.pageSize"
            @onChange="getTableList" :total="pages.total"></pb-pagination>
        </div>
      </pb-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getImportHistory } from '@/api/incomeStatistics'
import dayjs from "dayjs"
const downHistryFn = async (row) => {
  try {
    // 1. 创建临时a标签
    const a = document.createElement('a');
    a.style.display = 'none';
    document.body.appendChild(a);

    // 2. 处理不同浏览器的兼容性
    const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

    if (isSafari) {
      // 特殊处理Safari浏览器
      const iframe = document.createElement('iframe');
      iframe.style.display = 'none';
      iframe.src = row.fileUrl;
      document.body.appendChild(iframe);

      setTimeout(() => {
        document.body.removeChild(iframe);
        a.href = row.fileUrl;
        a.download = decodeURIComponent(row.fileName);
        a.click();
      }, 100);
    } else {
      // 3. 通用下载方法
      const response = await fetch(row.fileUrl);
      const blob = await response.blob();
      const url = URL.createObjectURL(blob);

      a.href = url;
      a.download = decodeURIComponent(row.fileName);
      a.click();

      // 4. 释放内存
      setTimeout(() => URL.revokeObjectURL(url), 1000);
    }

    // 5. 移除临时元素
    document.body.removeChild(a);
  } catch (error) {
    console.error('文件下载失败:', error);
    ElMessage.error('文件下载失败，请检查网络连接');
  }
};
const formOrigin = () => ({
  startDate: dayjs().startOf('week').format('YYYY-MM-DD'),
  stopDate: dayjs().endOf('week').format('YYYY-MM-DD'),
});
const incomeForm = ref(formOrigin());
const pageInit = () => ({
  total: 0,
  currentPage: 1,
  pageSize: 10,
});
const pages = ref(pageInit());


// 设置时间
const planDateRang = ref([incomeForm.value.startDate, incomeForm.value.stopDate])
const dateChange = () => {
  incomeForm.value.startDate = dayjs(planDateRang.value[0]).format('YYYY-MM-DD')
  incomeForm.value.stopDate = dayjs(planDateRang.value[1]).format('YYYY-MM-DD')
}

const tableColumn = reactive([
  {
    key: "createTime",
    name: "导入时间",
  },
  {
    key: "creator",
    name: "操作人",
  },
  {
    key: "fileName",
    name: "文件名称",
  },
  {
    slot: "operate",
    align: 'right',
    name: "操作",
  },

])
const tableData = ref([] as any)
const searchFn = () => {
  getTableList()
}
const resetFn = () => {
  incomeForm.value = formOrigin()
  pages.value = pageInit()
  getTableList()
}

const getTableList = () => {
  return new Promise<void>((resolve, reject) => {
    let { pageSize, currentPage } = pages.value
    let params = {
      pageSize, currentPage,
      ...incomeForm.value
    }
    getImportHistory(params).then(res => {
      if (res.code == 2000) {
        tableData.value = res.data.records
        pages.value.total = res.data.total

      }
    })
  })
}

onMounted(() => {
  getTableList()
})


const downStatisticFN = () => {
  // DownStatisticsxcelApi({
  //   ...incomeForm.value
  // }).then(response => {
  //   const disposition = response.headers['content-disposition'];
  //   // const filenameMatch = disposition.match(/filename*=utf-8''\s*([^;]+)/); 没用的东西
  //   const parts = disposition.split("filename*=utf-8''"); // 注意这里的分割字符串，它包含了一个空的单引号来匹配格式
  //   const encodedFilenamePart = parts[1] ? parts[1].split(';')[0] : null; // 分割出可能包含文件名的部分，并截取到下一个分号之前
  //   let decodedFilename = ''
  //   if (encodedFilenamePart) {
  //     // 解码文件名
  //     decodedFilename = decodeURIComponent(encodedFilenamePart);
  //     decodedFilename = decodedFilename.replace(/\(.*?\)/, '');
  //   } else {
  //     decodedFilename = "食堂消费统计" + new Date().getTime() + '.xlsx'
  //     // 如果没有找到包含文件名的部分，输出警告信息
  //     // console.warn("No filename part found in the Content-Disposition header using the simplified method.");
  //   }
  //   let blob = new Blob([response.data]);
  //   let downloadElement = document.createElement("a");
  //   let href = window.URL.createObjectURL(blob); //创建下载的链接
  //   downloadElement.href = href;
  //   downloadElement.download = decodedFilename; //下载后文件名
  //   document.body.appendChild(downloadElement);
  //   downloadElement.click(); //点击下载
  //   document.body.removeChild(downloadElement); //下载完成移除元素
  //   window.URL.revokeObjectURL(href); //释放掉blob对象
  // })
}

</script>

<style lang="scss" scoped></style>